import styles from './style.less'
import { Select } from 'antd';
import { useEffect } from 'react';
import { connect } from 'umi';
import UserBrief from '../UserBrief';
import ArrayUtils from '@/utils/ArrayUtils';
import { useState } from 'react';
import classNames from 'classnames';

const { Option } = Select;


const EnterpriseUserSelect = (props) => {
    const {
        dispatch,
        enterprseUserList = [],
        projectUserList = [],
        value,
        defaultValue,
        onChange,
        ismultiple,
        params,
        disabled,
        projectId,
        defaultOpen,
        onBlur,
        myInfo,
        allowClear = false,
        defaultMy,
        className
    } = props;

    useEffect(() => {
        // console.log('----11')
        if (dispatch) {
            if (projectId) {
                if (!projectUserList || projectUserList.length === 0) {
                    dispatch({
                        type: 'project/listUser',
                        payload: {
                            projectId: projectId,
                            params: params
                        }
                    })
                }
            } else {
                if (!enterprseUserList || enterprseUserList.length === 0) {
                    dispatch({
                        type: 'enterprise/listUserBriefByEnterpriseId',
                        payload: params
                    })
                }
            }
        }

    }, [])

    useEffect(() => {
        const userList = projectId ? projectUserList : enterprseUserList;
        if (userList && userList.length > 0) {
            let defaultUserId = value || defaultValue;
            if (defaultUserId) {
                setRealValue(defaultUserId)
                return;
            }
            const userIds = userList ? userList.map(item => item.id) : []
            if (defaultMy && myInfo && userIds.indexOf(myInfo.id) >= 0) {
                onChange(myInfo.id)
                setRealValue(myInfo.id)
            }
        }

    }, [projectUserList, enterprseUserList, myInfo])

    const [realValue, setRealValue] = useState();

    const onSelectBlur = () => {
        if (onBlur) {
            onBlur()
        }
    }
    const onValueChange = (value) => {
        setRealValue(value)
        if (ismultiple) {
            if (onChange) {
                const userList = projectId ? projectUserList : enterprseUserList;
                let users = [];
                for (let index in value) {
                    users.push(ArrayUtils.findOne(userList, item => item.id === value[index]))
                }
                onChange(value, users)
            }
        } else {
            if (onChange) {
                const userList = projectId ? projectUserList : enterprseUserList;
                let user = ArrayUtils.findOne(userList, item => item.id === value)
                onChange(value, user)
            }
        }
    }
    const onFocus = () => {
        if (dispatch) {
            // dispatch({
            //     type: 'enterprise/listUserBriefByEnterpriseId',
            //     payload: enterpriseId
            // })
        }
    }
    const onSearch = () => {
        // console.log('sdsdfds')
    }
    const userList = projectId ? projectUserList : enterprseUserList;
    // 如果列表中没有 初始值的 userId 展示不存在的用户
    if (realValue) {
        const userIds = userList.map(user => user.Id);
        if (Array.isArray(realValue)) {
            realValue.forEach((userId) => {
                if (!userIds.indexOf(userId)) {
                    userList.push({
                        nickName: "未知用户",
                        id: userId,
                    })
                }
            })
        } else {
            if (!userIds.indexOf(realValue)) {
                userList.push({
                    nickName: "未知用户",
                    id: realValue,
                })
            }
        }
    }
    const selectClassName = classNames(styles.userSelect, className)
    return (
        <Select
            disabled={disabled}
            showSearch
            allowClear={allowClear}
            onBlur={onBlur}
            placeholder="请选择用户"
            mode={ismultiple ? "multiple" : ""}
            onChange={onValueChange}
            onFocus={onFocus}
            onBlur={onSelectBlur}
            defaultOpen={defaultOpen}
            value={realValue}
            optionLabelProp="label"
            onSearch={onSearch}
            className={selectClassName}
            maxTagCount={10}
            filterOption={(input, option) =>
                option.text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
        >
            {userList.map((item) => (
                <Select.Option value={`${item.id}`} key={item.id} text={`${item.nickName}/${item.username}/${item.phone}`} label={item.nickName}>
                    <UserBrief user={item} showUsername={false} onClick={() => { }}>
                    </UserBrief>
                </Select.Option>
            ))}
        </Select>
    )

}

export default connect(({ user, enterprise, project }) => ({
    myInfo: user.myInfo,
    enterprseUserList: enterprise.enterpriseUserBriefList,
    projectUserList: project.userPage && project.userPage.list.map(item => item.user)
}))(EnterpriseUserSelect);
